package cn.anyubao.blog.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.*;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.Map;

/**
 * @Author huql
 * @Description 获取bean对象utils
 * @Date 11:39 下午 2021/1/4
 * @Param 
 * @return 
 **/
@Component
public class ApplicationContextUtils implements ApplicationContextAware, ApplicationEventPublisherAware {

    private static final Logger log = LoggerFactory.getLogger(ApplicationContextUtils.class);

    private static ApplicationContext applicationContext;

    private static ApplicationEventPublisher eventPublisher;

    public ApplicationContextUtils() {
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) {
        ApplicationContextUtils.applicationContext = applicationContext;
    }

    @Override
    public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
        eventPublisher = applicationEventPublisher;
    }

    public static boolean containsBean(String name) {
        if (applicationContext != null && StringUtils.hasText(name)) {
            return applicationContext.containsBean(name);
        } else {
            log.warn("[applicationContext]参数无效:{}", name);
            return false;
        }
    }

    public static Object getBean(String name) {
        return containsBean(name) ? applicationContext.getBean(name) : null;
    }

    public static <T> T getBean(Class<T> requiredType) {
        return applicationContext.getBean(requiredType);
    }

    public static <T> T getBean(String name, Class<T> requiredType) {
        return containsBean(name) ? applicationContext.getBean(name, requiredType) : null;
    }

    public static <T> Map<String, T> getBeansOfType(Class<T> requiredType) {
        return applicationContext.getBeansOfType(requiredType);
    }

    public static void publishEvent(ApplicationEvent event) {
        if (eventPublisher != null && event != null) {
            eventPublisher.publishEvent(event);
        } else {
            log.warn("[applicationEventPublisher]参数无效:{}", event);
        }
    }

}
